<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>风控规则引擎 - 系统管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f8f9fa;
        }
        .card {
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .card-header {
            background-color: #4a6fa5;
            color: white;
            font-weight: 600;
            border-radius: 8px 8px 0 0;
        }
        .form-label {
            font-weight: 500;
            color: #495057;
        }
        .btn-primary {
            background-color: #4a6fa5;
            border-color: #4a6fa5;
        }
        .btn-primary:hover {
            background-color: #3d5b8c;
            border-color: #3d5b8c;
        }
        .rule-card {
            border-left: 4px solid #4a6fa5;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .rule-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        .rule-card.active {
            border-left-color: #28a745;
        }
        .rule-card.inactive {
            border-left-color: #6c757d;
            opacity: 0.8;
        }
        .status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-active {
            background-color: #d4edda;
            color: #155724;
        }
        .status-inactive {
            background-color: #e9ecef;
            color: #6c757d;
        }
        .action-button {
            min-width: 80px;
        }
        .priority-badge {
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        .priority-high {
            background-color: #f8d7da;
            color: #721c24;
        }
        .priority-medium {
            background-color: #fff3cd;
            color: #856404;
        }
        .priority-low {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        .condition-item {
            padding: 8px;
            margin-bottom: 8px;
            background-color: #f8f9fa;
            border-radius: 4px;
            border: 1px solid #dee2e6;
        }
        .action-item {
            padding: 8px;
            margin-bottom: 8px;
            background-color: #e9ecef;
            border-radius: 4px;
            border: 1px solid #dee2e6;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="row align-items-center justify-content-between">
                            <div class="col">
                                <h3 class="mb-0">风控规则管理</h3>
                            </div>
                            <div class="col-auto">
                                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRuleModal">
                                    <i class="bi bi-plus"></i> 添加规则
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- 搜索和筛选 -->
                        <div class="row mb-4">
                            <div class="col-md-4">
                                <input type="text" id="searchInput" class="form-control" placeholder="搜索规则名称...">
                            </div>
                            <div class="col-md-2">
                                <select id="statusFilter" class="form-select">
                                    <option value="all">全部状态</option>
                                    <option value="active">启用</option>
                                    <option value="inactive">禁用</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <select id="priorityFilter" class="form-select">
                                    <option value="all">全部优先级</option>
                                    <option value="high">高</option>
                                    <option value="medium">中</option>
                                    <option value="low">低</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <select id="sceneFilter" class="form-select">
                                    <option value="all">全部场景</option>
                                    <option value="withdrawal">提现</option>
                                    <option value="login">登录</option>
                                    <option value="payment">支付</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <button type="button" class="btn btn-primary w-100" id="refreshRulesBtn">
                                    刷新规则
                                </button>
                            </div>
                        </div>

                        <!-- 规则列表 -->
                        <div id="rulesList" class="space-y-3">
                            <!-- 规则卡片将通过JS动态加载 -->
                            <div class="text-center py-4">
                                <div class="spinner-border" role="status">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                                <p class="mt-2">正在加载规则...</p>
                            </div>
                        </div>

                        <!-- 分页 -->
                        <div class="d-flex justify-content-center mt-4">
                            <nav aria-label="Page navigation">
                                <ul class="pagination" id="pagination">
                                    <!-- 分页将通过JS动态加载 -->
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>

                <!-- 规则执行日志 -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="mb-0">规则执行日志</h3>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>执行时间</th>
                                        <th>规则名称</th>
                                        <th>场景</th>
                                        <th>执行结果</th>
                                        <th>触发条件</th>
                                        <th>执行动作</th>
                                        <th>操作人</th>
                                    </tr>
                                </thead>
                                <tbody id="executionLogs">
                                    <!-- 日志记录将通过JS动态加载 -->
                                    <tr>
                                        <td colspan="7" class="text-center">
                                            <div class="spinner-border" role="status">
                                                <span class="visually-hidden">加载中...</span>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加规则模态框 -->
    <div class="modal fade" id="addRuleModal" tabindex="-1" aria-labelledby="addRuleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="addRuleModalLabel">添加风控规则</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addRuleForm">
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label for="ruleName" class="form-label">规则名称</label>
                                <input type="text" class="form-control" id="ruleName" name="ruleName" required>
                            </div>
                            <div class="col-md-6">
                                <label for="ruleCode" class="form-label">规则代码</label>
                                <input type="text" class="form-control" id="ruleCode" name="ruleCode" required>
                            </div>
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-md-4">
                                <label for="scene" class="form-label">应用场景</label>
                                <select class="form-select" id="scene" name="scene" required>
                                    <option value="withdrawal">提现</option>
                                    <option value="login">登录</option>
                                    <option value="payment">支付</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="priority" class="form-label">优先级</label>
                                <select class="form-select" id="priority" name="priority" required>
                                    <option value="high">高</option>
                                    <option value="medium">中</option>
                                    <option value="low">低</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="status" class="form-label">状态</label>
                                <select class="form-select" id="status" name="status" required>
                                    <option value="active">启用</option>
                                    <option value="inactive">禁用</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-4">
                            <label for="description" class="form-label">规则描述</label>
                            <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                        </div>
                        
                        <!-- 条件配置 -->
                        <div class="mb-4">
                            <label class="form-label">触发条件</label>
                            <div id="conditionsList">
                                <div class="condition-item">
                                    <div class="row">
                                        <div class="col-md-3">
                                            <select class="form-select">
                                                <option value="amount">金额</option>
                                                <option value="frequency">频率</option>
                                                <option value="ip">IP地址</option>
                                                <option value="location">地理位置</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <select class="form-select">
                                                <option value="gt">大于</option>
                                                <option value="lt">小于</option>
                                                <option value="eq">等于</option>
                                                <option value="neq">不等于</option>
                                                <option value="in">包含</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <input type="text" class="form-control" placeholder="条件值">
                                        </div>
                                        <div class="col-md-3">
                                            <select class="form-select">
                                                <option value="daily">每日</option>
                                                <option value="weekly">每周</option>
                                                <option value="monthly">每月</option>
                                                <option value="total">累计</option>
                                            </select>
                                        </div>
                                        <div class="col-md-1">
                                            <button type="button" class="btn btn-danger btn-sm w-100">×</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-secondary btn-sm mt-2">添加条件</button>
                        </div>
                        
                        <!-- 动作配置 -->
                        <div class="mb-4">
                            <label class="form-label">执行动作</label>
                            <div id="actionsList">
                                <div class="action-item">
                                    <div class="row">
                                        <div class="col-md-5">
                                            <select class="form-select">
                                                <option value="reject">拒绝</option>
                                                <option value="review">人工审核</option>
                                                <option value="alert">告警</option>
                                                <option value="limit">限制</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <input type="text" class="form-control" placeholder="动作参数">
                                        </div>
                                        <div class="col-md-1">
                                            <button type="button" class="btn btn-danger btn-sm w-100">×</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-secondary btn-sm mt-2">添加动作</button>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveRuleBtn">保存规则</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑规则模态框 -->
    <div class="modal fade" id="editRuleModal" tabindex="-1" aria-labelledby="editRuleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="editRuleModalLabel">编辑风控规则</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editRuleForm">
                        <input type="hidden" id="editRuleId" name="ruleId">
                        <!-- 表单内容与添加规则模态框相同 -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label for="editRuleName" class="form-label">规则名称</label>
                                <input type="text" class="form-control" id="editRuleName" name="ruleName" required>
                            </div>
                            <div class="col-md-6">
                                <label for="editRuleCode" class="form-label">规则代码</label>
                                <input type="text" class="form-control" id="editRuleCode" name="ruleCode" required disabled>
                            </div>
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-md-4">
                                <label for="editScene" class="form-label">应用场景</label>
                                <select class="form-select" id="editScene" name="scene" required>
                                    <option value="withdrawal">提现</option>
                                    <option value="login">登录</option>
                                    <option value="payment">支付</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="editPriority" class="form-label">优先级</label>
                                <select class="form-select" id="editPriority" name="priority" required>
                                    <option value="high">高</option>
                                    <option value="medium">中</option>
                                    <option value="low">低</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="editStatus" class="form-label">状态</label>
                                <select class="form-select" id="editStatus" name="status" required>
                                    <option value="active">启用</option>
                                    <option value="inactive">禁用</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-4">
                            <label for="editDescription" class="form-label">规则描述</label>
                            <textarea class="form-control" id="editDescription" name="description" rows="3"></textarea>
                        </div>
                        
                        <!-- 条件和动作配置 -->
                        <div class="mb-4">
                            <label class="form-label">触发条件</label>
                            <div id="editConditionsList">
                                <!-- 动态生成 -->
                            </div>
                            <button type="button" class="btn btn-secondary btn-sm mt-2">添加条件</button>
                        </div>
                        
                        <div class="mb-4">
                            <label class="form-label">执行动作</label>
                            <div id="editActionsList">
                                <!-- 动态生成 -->
                            </div>
                            <button type="button" class="btn btn-secondary btn-sm mt-2">添加动作</button>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="updateRuleBtn">更新规则</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 规则详情模态框 -->
    <div class="modal fade" id="ruleDetailModal" tabindex="-1" aria-labelledby="ruleDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="ruleDetailModalLabel">规则详情</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="ruleDetailContent">
                        <!-- 规则详情将通过JS动态加载 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化变量
            let currentPage = 1;
            let totalPages = 1;
            let currentRuleId = null;
            
            // 从URL参数或localStorage获取token
            function getToken() {
                try {
                    // 首先从URL参数中获取token
                    const urlParams = new URLSearchParams(window.location.search);
                    const urlToken = urlParams.get('token');
                    
                    if (urlToken) {
                        // 将URL中的token存储到localStorage
                        localStorage.setItem('token', urlToken);
                        return urlToken;
                    }
                    
                    // 然后从localStorage中获取token
                    const storageToken = localStorage.getItem('token');
                    if (storageToken) {
                        return storageToken;
                    }
                    
                    // 如果都没有，则重定向到登录页面
                    window.location.href = '/login';
                    return null;
                } catch (error) {
                    console.error('获取token时发生错误:', error);
                    window.location.href = '/login';
                    return null;
                }
            }

            // 处理Token过期
            function handleTokenExpiration() {
                console.log('Token已过期或无效，请重新登录');
                alert('您的会话已过期，请重新登录');
                window.location.href = '/login';
            }
            
            // 加载规则列表
            loadRules();
            
            // 加载执行日志
            loadExecutionLogs();
            
            // 搜索输入事件
            document.getElementById('searchInput').addEventListener('input', function() {
                currentPage = 1;
                loadRules();
            });
            
            // 筛选条件变化事件
            document.getElementById('statusFilter').addEventListener('change', function() {
                currentPage = 1;
                loadRules();
            });
            
            document.getElementById('priorityFilter').addEventListener('change', function() {
                currentPage = 1;
                loadRules();
            });
            
            document.getElementById('sceneFilter').addEventListener('change', function() {
                currentPage = 1;
                loadRules();
            });
            
            // 刷新按钮点击事件
            document.getElementById('refreshRulesBtn').addEventListener('click', function() {
                currentPage = 1;
                loadRules();
            });
            
            // 保存规则按钮点击事件
            document.getElementById('saveRuleBtn').addEventListener('click', function() {
                saveRule();
            });
            
            // 更新规则按钮点击事件
            document.getElementById('updateRuleBtn').addEventListener('click', function() {
                updateRule();
            });
            
            // 加载规则列表
            async function loadRules() {
                try {
                    const token = getToken();
                    if (!token) return;
                    
                    const searchText = document.getElementById('searchInput').value;
                    const statusFilter = document.getElementById('statusFilter').value;
                    const priorityFilter = document.getElementById('priorityFilter').value;
                    const sceneFilter = document.getElementById('sceneFilter').value;
                    
                    console.log('加载规则列表，当前页:', currentPage);
                    console.log('搜索条件:', searchText, statusFilter, priorityFilter, sceneFilter);
                    
                    const baseUrl = window.location.origin;
                    const apiUrl = `${baseUrl}/v1/risk_control/rules?page=${currentPage}&page_size=10&search=${encodeURIComponent(searchText)}&status=${statusFilter}&priority=${priorityFilter}&scene=${sceneFilter}`;
                    console.log('API调用路径:', apiUrl);
                    
                    const response = await fetch(apiUrl, {
                        headers: {
                            'x-token': token,
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (!response.ok) {
                        if (response.status === 401) {
                            handleTokenExpiration();
                            return;
                        }
                        throw new Error(`获取规则列表失败，状态码: ${response.status}`);
                    }
                    
                    const data = await response.json();
                    
                    // 兼容不同格式的响应
                    let rules = [];
                    let paginationInfo = { total: 0, page_size: 10 };
                    
                    if (data.code === 200 && data.data) {
                        rules = data.data.list || [];
                        paginationInfo = {
                            total: data.data.total || 0,
                            page_size: data.data.page_size || 10
                        };
                    } else if (data.list) {
                        rules = data.list;
                        paginationInfo = {
                            total: data.total || 0,
                            page_size: data.page_size || 10
                        };
                    }
                    
                    // 计算总页数
                    totalPages = Math.ceil(paginationInfo.total / paginationInfo.page_size);
                    
                    // 渲染规则列表
                    const rulesListContainer = document.getElementById('rulesList');
                    rulesListContainer.innerHTML = '';
                    
                    if (rules.length === 0) {
                        rulesListContainer.innerHTML = `
                            <div class="text-center py-4 text-muted">
                                暂无规则数据
                            </div>
                        `;
                    } else {
                        rules.forEach(rule => {
                            const ruleCard = document.createElement('div');
                            ruleCard.className = `card rule-card ${rule.status === 'active' ? 'active' : 'inactive'}`;
                            ruleCard.innerHTML = `
                                <div class="card-body">
                                    <div class="row align-items-start">
                                        <div class="col-md-7">
                                            <div class="d-flex items-center">
                                                <h5 class="card-title mb-0">${rule.name}</h5>
                                                <span class="status-badge ${rule.status === 'active' ? 'status-active' : 'status-inactive'} ml-2">
                                                    ${rule.status === 'active' ? '启用' : '禁用'}
                                                </span>
                                                <span class="priority-badge priority-${rule.priority} ml-2">
                                                    ${rule.priority === 'high' ? '高' : rule.priority === 'medium' ? '中' : '低'}优先级
                                                </span>
                                            </div>
                                            <p class="card-text text-muted mt-1">${rule.description || '暂无描述'}</p>
                                            <div class="mt-2">
                                                <small class="text-muted">场景: ${rule.scene === 'withdrawal' ? '提现' : rule.scene === 'login' ? '登录' : '支付'}</small>
                                                <small class="text-muted ml-3">规则代码: ${rule.code}</small>
                                                <small class="text-muted ml-3">创建时间: ${formatDate(rule.create_time)}</small>
                                            </div>
                                        </div>
                                        <div class="col-md-5 text-right">
                                            <div class="btn-group" role="group" aria-label="规则操作">
                                                <button type="button" class="btn btn-outline-primary btn-sm action-button view-rule" data-rule-id="${rule.id}">
                                                    查看
                                                </button>
                                                <button type="button" class="btn btn-outline-info btn-sm action-button edit-rule" data-rule-id="${rule.id}">
                                                    编辑
                                                </button>
                                                <button type="button" class="btn btn-outline-success btn-sm action-button toggle-rule" data-rule-id="${rule.id}">
                                                    ${rule.status === 'active' ? '禁用' : '启用'}
                                                </button>
                                                <button type="button" class="btn btn-outline-danger btn-sm action-button delete-rule" data-rule-id="${rule.id}">
                                                    删除
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            `;
                            rulesListContainer.appendChild(ruleCard);
                        });
                    }
                    
                    // 绑定规则操作按钮事件
                    document.querySelectorAll('.view-rule').forEach(btn => {
                        btn.addEventListener('click', function() {
                            viewRule(this.getAttribute('data-rule-id'));
                        });
                    });
                    
                    document.querySelectorAll('.edit-rule').forEach(btn => {
                        btn.addEventListener('click', function() {
                            editRule(this.getAttribute('data-rule-id'));
                        });
                    });
                    
                    document.querySelectorAll('.toggle-rule').forEach(btn => {
                        btn.addEventListener('click', function() {
                            toggleRuleStatus(this.getAttribute('data-rule-id'));
                        });
                    });
                    
                    document.querySelectorAll('.delete-rule').forEach(btn => {
                        btn.addEventListener('click', function() {
                            deleteRule(this.getAttribute('data-rule-id'));
                        });
                    });
                    
                    // 渲染分页
                    renderPagination();
                } catch (error) {
                    console.error('加载规则列表失败:', error);
                    document.getElementById('rulesList').innerHTML = `
                        <div class="text-center py-4 text-danger">
                            加载失败: ${error.message}
                        </div>
                    `;
                }
            }
            
            // 加载执行日志
            async function loadExecutionLogs() {
                try {
                    const token = getToken();
                    if (!token) return;
                    
                    const baseUrl = window.location.origin;
                    const apiUrl = `${baseUrl}/v1/risk_control/logs?page=1&page_size=10`;
                    console.log('API调用路径:', apiUrl);
                    
                    const response = await fetch(apiUrl, {
                        headers: {
                            'x-token': token,
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (!response.ok) {
                        if (response.status === 401) {
                            handleTokenExpiration();
                            return;
                        }
                        throw new Error(`获取执行日志失败，状态码: ${response.status}`);
                    }
                    
                    const data = await response.json();
                    
                    // 兼容不同格式的响应
                    let logs = [];
                    
                    if (data.code === 200 && data.data) {
                        logs = data.data.list || [];
                    } else if (data.list) {
                        logs = data.list;
                    }
                    
                    // 渲染执行日志
                    const logsContainer = document.getElementById('executionLogs');
                    logsContainer.innerHTML = '';
                    
                    if (logs.length === 0) {
                        logsContainer.innerHTML = `
                            <tr>
                                <td colspan="7" class="text-center text-muted">暂无执行日志</td>
                            </tr>
                        `;
                    } else {
                        logs.forEach(log => {
                            const resultClass = log.result === 'triggered' ? 'text-danger' : 'text-success';
                            const resultText = log.result === 'triggered' ? '已触发' : '未触发';
                            
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${formatDate(log.execution_time)}</td>
                                <td>${log.rule_name}</td>
                                <td>${log.scene === 'withdrawal' ? '提现' : log.scene === 'login' ? '登录' : '支付'}</td>
                                <td><span class="${resultClass}">${resultText}</span></td>
                                <td>${log.triggered_condition || '-'}</td>
                                <td>${log.executed_action || '-'}</td>
                                <td>${log.operator || '系统'}</td>
                            `;
                            logsContainer.appendChild(row);
                        });
                    }
                } catch (error) {
                    console.error('加载执行日志失败:', error);
                    document.getElementById('executionLogs').innerHTML = `
                        <tr>
                            <td colspan="7" class="text-center text-danger">加载失败: ${error.message}</td>
                        </tr>
                    `;
                }
            }
            
            // 保存规则
            async function saveRule() {
                try {
                    const token = getToken();
                    if (!token) return;
                    
                    const ruleName = document.getElementById('ruleName').value;
                    const ruleCode = document.getElementById('ruleCode').value;
                    const scene = document.getElementById('scene').value;
                    const priority = document.getElementById('priority').value;
                    const status = document.getElementById('status').value;
                    const description = document.getElementById('description').value;
                    
                    // 收集条件和动作数据
                    const conditions = [];
                    const actions = [];
                    
                    const ruleData = {
                        name: ruleName,
                        code: ruleCode,
                        scene: scene,
                        priority: priority,
                        status: status,
                        description: description,
                        conditions: conditions,
                        actions: actions
                    };
                    
                    const baseUrl = window.location.origin;
                    const apiUrl = `${baseUrl}/v1/risk_control/rules`;
                    
                    const response = await fetch(apiUrl, {
                        method: 'POST',
                        headers: {
                            'x-token': token,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(ruleData)
                    });
                    
                    if (!response.ok) {
                        if (response.status === 401) {
                            handleTokenExpiration();
                            return;
                        }
                        throw new Error(`保存规则失败，状态码: ${response.status}`);
                    }
                    
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('addRuleModal'));
                    modal.hide();
                    
                    // 重置表单
                    document.getElementById('addRuleForm').reset();
                    
                    // 刷新规则列表
                    loadRules();
                    
                    alert('规则保存成功');
                } catch (error) {
                    console.error('保存规则失败:', error);
                    alert(`保存规则失败: ${error.message}`);
                }
            }
            
            // 更新规则
            async function updateRule() {
                try {
                    const token = getToken();
                    if (!token || !currentRuleId) return;
                    
                    const ruleName = document.getElementById('editRuleName').value;
                    const scene = document.getElementById('editScene').value;
                    const priority = document.getElementById('editPriority').value;
                    const status = document.getElementById('editStatus').value;
                    const description = document.getElementById('editDescription').value;
                    
                    // 收集条件和动作数据
                    const conditions = [];
                    const actions = [];
                    
                    const ruleData = {
                        name: ruleName,
                        scene: scene,
                        priority: priority,
                        status: status,
                        description: description,
                        conditions: conditions,
                        actions: actions
                    };
                    
                    const baseUrl = window.location.origin;
                    const apiUrl = `${baseUrl}/v1/risk_control/rules/${currentRuleId}`;
                    
                    const response = await fetch(apiUrl, {
                        method: 'PUT',
                        headers: {
                            'x-token': token,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(ruleData)
                    });
                    
                    if (!response.ok) {
                        if (response.status === 401) {
                            handleTokenExpiration();
                            return;
                        }
                        throw new Error(`更新规则失败，状态码: ${response.status}`);
                    }
                    
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('editRuleModal'));
                    modal.hide();
                    
                    // 刷新规则列表
                    loadRules();
                    
                    alert('规则更新成功');
                } catch (error) {
                    console.error('更新规则失败:', error);
                    alert(`更新规则失败: ${error.message}`);
                }
            }
            
            // 查看规则详情
            async function viewRule(ruleId) {
                try {
                    const token = getToken();
                    if (!token) return;
                    
                    const baseUrl = window.location.origin;
                    const apiUrl = `${baseUrl}/v1/risk_control/rules/${ruleId}`;
                    
                    const response = await fetch(apiUrl, {
                        headers: {
                            'x-token': token,
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (!response.ok) {
                        if (response.status === 401) {
                            handleTokenExpiration();
                            return;
                        }
                        throw new Error(`获取规则详情失败，状态码: ${response.status}`);
                    }
                    
                    const data = await response.json();
                    const rule = data.data || data;
                    
                    // 填充规则详情
                    const detailContent = document.getElementById('ruleDetailContent');
                    detailContent.innerHTML = `
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <h5>基本信息</h5>
                                <dl class="row">
                                    <dt class="col-sm-4">规则名称:</dt>
                                    <dd class="col-sm-8">${rule.name}</dd>
                                    <dt class="col-sm-4">规则代码:</dt>
                                    <dd class="col-sm-8">${rule.code}</dd>
                                    <dt class="col-sm-4">应用场景:</dt>
                                    <dd class="col-sm-8">${rule.scene === 'withdrawal' ? '提现' : rule.scene === 'login' ? '登录' : '支付'}</dd>
                                    <dt class="col-sm-4">优先级:</dt>
                                    <dd class="col-sm-8">${rule.priority === 'high' ? '高' : rule.priority === 'medium' ? '中' : '低'}</dd>
                                    <dt class="col-sm-4">状态:</dt>
                                    <dd class="col-sm-8"><span class="status-badge ${rule.status === 'active' ? 'status-active' : 'status-inactive'}">${rule.status === 'active' ? '启用' : '禁用'}</span></dd>
                                </dl>
                            </div>
                            <div class="col-md-6">
                                <h5>时间信息</h5>
                                <dl class="row">
                                    <dt class="col-sm-4">创建时间:</dt>
                                    <dd class="col-sm-8">${formatDate(rule.create_time)}</dd>
                                    <dt class="col-sm-4">更新时间:</dt>
                                    <dd class="col-sm-8">${formatDate(rule.update_time || rule.create_time)}</dd>
                                    <dt class="col-sm-4">最后执行:</dt>
                                    <dd class="col-sm-8">${rule.last_execution_time ? formatDate(rule.last_execution_time) : '未执行'}</dd>
                                    <dt class="col-sm-4">触发次数:</dt>
                                    <dd class="col-sm-8">${rule.trigger_count || 0} 次</dd>
                                </dl>
                            </div>
                        </div>
                        <div class="mb-4">
                            <h5>规则描述</h5>
                            <p>${rule.description || '暂无描述'}</p>
                        </div>
                        <div class="mb-4">
                            <h5>触发条件</h5>
                            <div>${rule.conditions && rule.conditions.length > 0 ? 
                                rule.conditions.map(c => 
                                    `<div class="condition-item">${c.field} ${c.operator} ${c.value} ${c.time_window || ''}</div>`
                                ).join('') : 
                                '<p class="text-muted">暂无条件</p>'
                            }</div>
                        </div>
                        <div>
                            <h5>执行动作</h5>
                            <div>${rule.actions && rule.actions.length > 0 ? 
                                rule.actions.map(a => 
                                    `<div class="action-item">${a.type} ${a.params || ''}</div>`
                                ).join('') : 
                                '<p class="text-muted">暂无动作</p>'
                            }</div>
                        </div>
                    `;
                    
                    // 显示模态框
                    const modal = new bootstrap.Modal(document.getElementById('ruleDetailModal'));
                    modal.show();
                } catch (error) {
                    console.error('查看规则详情失败:', error);
                    alert(`查看规则详情失败: ${error.message}`);
                }
            }
            
            // 编辑规则
            async function editRule(ruleId) {
                try {
                    const token = getToken();
                    if (!token) return;
                    
                    currentRuleId = ruleId;
                    
                    const baseUrl = window.location.origin;
                    const apiUrl = `${baseUrl}/v1/risk_control/rules/${ruleId}`;
                    
                    const response = await fetch(apiUrl, {
                        headers: {
                            'x-token': token,
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (!response.ok) {
                        if (response.status === 401) {
                            handleTokenExpiration();
                            return;
                        }
                        throw new Error(`获取规则详情失败，状态码: ${response.status}`);
                    }
                    
                    const data = await response.json();
                    const rule = data.data || data;
                    
                    // 填充表单
                    document.getElementById('editRuleId').value = rule.id;
                    document.getElementById('editRuleName').value = rule.name;
                    document.getElementById('editRuleCode').value = rule.code;
                    document.getElementById('editScene').value = rule.scene;
                    document.getElementById('editPriority').value = rule.priority;
                    document.getElementById('editStatus').value = rule.status;
                    document.getElementById('editDescription').value = rule.description || '';
                    
                    // 填充条件和动作（这里简化处理）
                    
                    // 显示模态框
                    const modal = new bootstrap.Modal(document.getElementById('editRuleModal'));
                    modal.show();
                } catch (error) {
                    console.error('编辑规则失败:', error);
                    alert(`编辑规则失败: ${error.message}`);
                }
            }
            
            // 切换规则状态
            async function toggleRuleStatus(ruleId) {
                try {
                    const token = getToken();
                    if (!token) return;
                    
                    const baseUrl = window.location.origin;
                    const apiUrl = `${baseUrl}/v1/risk_control/rules/${ruleId}/status`;
                    
                    const response = await fetch(apiUrl, {
                        method: 'PUT',
                        headers: {
                            'x-token': token,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({})
                    });
                    
                    if (!response.ok) {
                        if (response.status === 401) {
                            handleTokenExpiration();
                            return;
                        }
                        throw new Error(`切换规则状态失败，状态码: ${response.status}`);
                    }
                    
                    // 刷新规则列表
                    loadRules();
                    
                    alert('规则状态切换成功');
                } catch (error) {
                    console.error('切换规则状态失败:', error);
                    alert(`切换规则状态失败: ${error.message}`);
                }
            }
            
            // 删除规则
            async function deleteRule(ruleId) {
                try {
                    if (!confirm('确定要删除这条规则吗？此操作不可撤销。')) {
                        return;
                    }
                    
                    const token = getToken();
                    if (!token) return;
                    
                    const baseUrl = window.location.origin;
                    const apiUrl = `${baseUrl}/v1/risk_control/rules/${ruleId}`;
                    
                    const response = await fetch(apiUrl, {
                        method: 'DELETE',
                        headers: {
                            'x-token': token,
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (!response.ok) {
                        if (response.status === 401) {
                            handleTokenExpiration();
                            return;
                        }
                        throw new Error(`删除规则失败，状态码: ${response.status}`);
                    }
                    
                    // 刷新规则列表
                    loadRules();
                    
                    alert('规则删除成功');
                } catch (error) {
                    console.error('删除规则失败:', error);
                    alert(`删除规则失败: ${error.message}`);
                }
            }
            
            // 渲染分页
            function renderPagination() {
                const pagination = document.getElementById('pagination');
                pagination.innerHTML = '';
                
                // 上一页
                const prevLi = document.createElement('li');
                prevLi.className = `page-item ${currentPage <= 1 ? 'disabled' : ''}`;
                prevLi.innerHTML = `
                    <a class="page-link" href="#" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                `;
                prevLi.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (currentPage > 1) {
                        currentPage--;
                        loadRules();
                    }
                });
                pagination.appendChild(prevLi);
                
                // 页码
                const maxVisiblePages = 5;
                let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
                let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
                
                if (endPage - startPage + 1 < maxVisiblePages) {
                    startPage = Math.max(1, endPage - maxVisiblePages + 1);
                }
                
                for (let i = startPage; i <= endPage; i++) {
                    const li = document.createElement('li');
                    li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                    li.innerHTML = `<a class="page-link" href="#">${i}</a>`;
                    li.addEventListener('click', function(e) {
                        e.preventDefault();
                        if (i !== currentPage) {
                            currentPage = i;
                            loadRules();
                        }
                    });
                    pagination.appendChild(li);
                }
                
                // 下一页
                const nextLi = document.createElement('li');
                nextLi.className = `page-item ${currentPage >= totalPages ? 'disabled' : ''}`;
                nextLi.innerHTML = `
                    <a class="page-link" href="#" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                `;
                nextLi.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (currentPage < totalPages) {
                        currentPage++;
                        loadRules();
                    }
                });
                pagination.appendChild(nextLi);
            }
            
            // 辅助函数：格式化日期
            function formatDate(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            }
        });
    </script>
</body>
</html>